Andrew McCutchen hit a three-run homer, Ke'Bryan Hayes a two-run double and Carlos Santana and Austin Hedges an RBI single apiece for the Pirates.
Texas built a six-run lead before Nick Senzel put Cincinnati on the scoreboard with an RBI single in the seventh inning.
Ruiz's homer and Joey Meneses' RBI single in the third against Jose Butto (0-1) provided an early cushion for Gray.
The Brewers got single runs in the third and fourth, then pulled within 4-3 when Rowdy Tellez opened the sixth with his eighth homer.
With two outs during Chicago's four-run eighth, Gomes lined an RBI single to right field for his fifth career four-hit game.